package com.scut.fy.notice.service.impl;

import com.scut.fy.notice.service.EmailService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

/**
 * TODO
 *
 * @author JY
 * @version 1.0
 * @date 2021/8/28
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Value("spring.mail.username")
    private String from;
    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public void sendSimpleMail(String subject, String text, String to) {
        try {
            log.info("开始发送邮件到={}", to);
            String f = StringUtils.isBlank(from) ? "itsams@163.com" : from;
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(subject);
            message.setText(text);
            message.setFrom(f);
            message.setTo(to);
            message.setSentDate(new Date());
            javaMailSender.send(message);
            log.info("邮件已发送");
        } catch (Exception e){
            log.error("邮件发送失败");
            e.printStackTrace();
        }

    }

    @Override
    public void sendAttachMail(String subject, String text, String to, String attachName, String attachAddress) {
        try {
            log.info("开始发送邮件到={}", to);
            String f = StringUtils.isBlank(from) ? "itsams@163.com" : from;
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject(subject);
            helper.setFrom(f);
            helper.setTo(to);
            helper.setText(text);
            helper.setSentDate(new Date());
            helper.addAttachment(attachName, new File(attachAddress));
            javaMailSender.send(mimeMessage);
            log.info("邮件已发送");
        } catch (MessagingException e) {
            log.error("邮件发送失败");
            e.printStackTrace();
        }

    }

    @Override
    public void sendThymeleafMail(String subject, String to) {

    }

}
